package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * @author jay
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        // 解决缓存穿透
        Shop shop = cacheClient.queryWithPassThrough(
                Shop.class, id, CACHE_SHOP_KEY, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        // 互斥锁解决缓存击穿
//        Shop shop = queryWithMutex(id);
        // 逻辑过期解决缓存击穿
//        Shop shop = cacheClient.queryWithLogicalExpire(
//                id, CACHE_SHOP_KEY, Shop.class, LOCK_SHOP_KEY, this::getById, 20L);
        if (shop == null) {
            return Result.fail("店铺不存在！");
        }
        // 返回
        return Result.ok(shop);
    }

    /**
     * 逻辑过期解决缓存击穿
     */
//    public Shop queryWithLogicalExpire(Long id) {
//        //从redis查缓存
//        String shopKey = CACHE_SHOP_KEY + id;
//        String cacheShop = stringRedisTemplate.opsForValue().get(shopKey);
//        //判断是否存在
//        if (StrUtil.isBlank(cacheShop)) {
//            //不存在，直接返回
//            return null;
//        }
//        // 命中，先把json反序列化为对象
//        RedisData redisData = JSONUtil.toBean(cacheShop, RedisData.class);
//        JSONObject data = (JSONObject) redisData.getData(); //因为序列化过了，data其本质为JSONObject对象
//        Shop shop = JSONUtil.toBean(data, Shop.class);
//        LocalDateTime expireTime = redisData.getExpireTime();
//        // 判断是否过期
//        if (expireTime.isAfter(LocalDateTime.now())) {
//            // 未过期，直接返回店铺信息
//            return shop;
//        }
//
//        // 已过期，缓存重建
//        // 获取互斥锁
//        String lockKey = LOCK_SHOP_KEY + id;
//        boolean isLock = tryLock(lockKey);
//        // 判断是否获取锁成功
//        if (isLock) {
//            // 成功，先再次检测redis缓存是否过期:
//            cacheShop = stringRedisTemplate.opsForValue().get(shopKey);
//            //判断是否存在
//            if (StrUtil.isBlank(cacheShop)) {
//                //不存在，直接返回
//                return null;
//            }
//            // 命中，先把json反序列化为对象
//            redisData = JSONUtil.toBean(cacheShop, RedisData.class);
//            data = (JSONObject) redisData.getData(); //因为序列化过了，data其本质为JSONObject对象
//            shop = JSONUtil.toBean(data, Shop.class);
//            expireTime = redisData.getExpireTime();
//            // 判断是否过期
//            if (expireTime.isAfter(LocalDateTime.now())) {
//                // 未过期，直接返回店铺信息
//                return shop;
//            }
//
//            // 然后开启独立线程
//            CACHE_REBUILD_EXECUTOR.submit(() -> {
//                try {
//                    //缓存重建任务
//                    saveShop2Redis(id, 20L);
//                } catch (Exception e) {
//                    throw new RuntimeException(e);
//                } finally {
//                    //释放锁
//                    unLock(lockKey);
//                }
//            });
//        }
//        return shop;
//    }

//    /**
//     * 线程池方式创建线程
//     */
//    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 加互斥锁解决缓存击穿
     */
    public Shop queryWithMutex(Long id) {
        //从redis查缓存
        String shopKey = CACHE_SHOP_KEY + id;
        String cacheShop = stringRedisTemplate.opsForValue().get(shopKey);
        //判断是否存在
        if (StrUtil.isNotBlank(cacheShop)) {
            //存在，转json后返回
            //更新时间
            stringRedisTemplate.expire(shopKey, CACHE_SHOP_TTL, TimeUnit.MINUTES);
            Shop shop = JSONUtil.toBean(cacheShop, Shop.class); // json转对象
            return shop;
        }
        //判断是否为空值""，避免缓存穿透
        if (cacheShop != null) {
            return null;
        }
        //不存在。
        //缓存重建步骤，避免缓存击穿。（互斥锁方式）
        String lockKey = LOCK_SHOP_KEY + id;
        Shop shop = null;
        // 整个try catch 是为了最后finally释放锁
        try {
            //1 获取互斥锁
            boolean isLock = tryLock(lockKey);
            //2 判断是否获取成功，失败则休眠并重试
            if (!isLock) {
                //失败,休眠并重试
                Thread.sleep(50);
                return shop;
            }
            //3 成功,则再次判断缓存是否存在
            Thread.sleep(200); // 模拟重建的延时
            cacheShop = stringRedisTemplate.opsForValue().get(shopKey);
            if (StrUtil.isNotBlank(cacheShop)) {
                //存在，转json后返回
                //更新时间
                stringRedisTemplate.expire(shopKey, CACHE_SHOP_TTL, TimeUnit.MINUTES);
                shop = JSONUtil.toBean(cacheShop, Shop.class); // json转对象
                return shop;
            }
            //判断是否为空值""，避免缓存穿透
            if (cacheShop != null) {
                return null;
            }

            // 继续以下步骤（数据写入缓存）
            //查询数据库，再判断是否存在于数据库
            shop = getById(id);
            if (shop == null) {
                //不存在。将空值写入redis，避免缓存穿透
                stringRedisTemplate.opsForValue().set(shopKey, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //存在。写入缓存且返回
            String strShop = JSONUtil.toJsonStr(shop); // 对象转json
            stringRedisTemplate.opsForValue().set(shopKey, strShop, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //释放互斥锁，避免缓存击穿
            unLock(lockKey);
        }
        return shop;
    }


    /**
     * 缓存穿透方式
     */
//    public Shop queryWithPassThrough(Long id) {
//        //从redis查缓存
//        String shopKey = CACHE_SHOP_KEY + id;
//        String cacheShop = stringRedisTemplate.opsForValue().get(shopKey);
//        //判断是否存在
//        if (StrUtil.isNotBlank(cacheShop)) {
//            //存在，转json后返回
//            //更新时间
//            stringRedisTemplate.expire(shopKey, CACHE_SHOP_TTL, TimeUnit.MINUTES);
//            return JSONUtil.toBean(cacheShop, Shop.class);
//        }
//        //判断是否为空值""，避免缓存穿透
//        if (cacheShop != null) {
//            return null;
//        }
//
//        //不存在。 查询数据库，再判断是否存在于数据库
//        Shop shop = getById(id);
//        if (shop == null) {
//            //不存在。将空值写入redis，避免缓存穿透
//            stringRedisTemplate.opsForValue().set(shopKey, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
//            return null;
//        }
//        //存在。写入缓存且返回
//        String strShop = JSONUtil.toJsonStr(shop); // 对象转json
//        stringRedisTemplate.opsForValue().set(shopKey, strShop, CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        return shop;
//    }

    /**
     * 获取锁
     */
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放锁
     */
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 逻辑过期方式缓存重建任务
     */
    public void saveShop3Redis(Long id, Long expireSeconds) throws InterruptedException {
        //查询店铺数据
        Shop shop = getById(id);
        Thread.sleep(200);//模拟重建缓存延迟
        //封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        if (shop.getId() == null) {
            return Result.fail("店铺id为空");
        }
        //更新数据库
        updateById(shop);

        //删除缓存
        String shopKey = CACHE_SHOP_KEY + shop.getId();
        stringRedisTemplate.delete(shopKey);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 判断是否需要根据坐标查询
        if(x == null || y == null){
            // 不需要，按数据库查
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }
        // 计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        // 查询redis, 按照距离排序、分页。结果：shopId、distance
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                // GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
                .search(key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs()
                                .includeDistance().limit(end)
                );
        if(results == null){
            return Result.ok(Collections.emptyList());
        }
        // 解析出id
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        // 判断from是否超出商铺个数
        if(list.size() <= from){
            return Result.ok(Collections.emptyList());
        }
        // 截取 from - end的部分 （滚动分页查询）
        List<Long> ids = new ArrayList<>(list.size()); // id集合
        Map<String, Distance> distanceMap = new HashMap<>(list.size()); //距离 Distance Map集合
        list.stream().skip(from).forEach(result -> {
            // 获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        // 根据id查询Shop
        String idsStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids)
                .last("order by field (id, " + idsStr + ")").list();
        // 将距离传入店铺
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        // 返回
        return Result.ok(shops);
    }
}
